package gameSite;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
	
	}

	
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
	    ServletContext thisContext = getServletContext(); 

		Cookie[] cookies = request.getCookies();
		
		System.out.println(cookies);
		System.out.println(cookies[1].getValue());
		System.out.println(cookies[2].getName());
		System.out.println(cookies[3].getName());
		
		String productIDStirng = cookies[1].getValue();
		int productID1 = Integer.parseInt(productIDStirng); 
		String sessionIDString = cookies[2].getValue();
		int sessionID = Integer.parseInt(sessionIDString);
		String userIDString = cookies[3].getValue();
		int userID = Integer.parseInt(userIDString);
		
		ProductTableGateway productTableGateway = new ProductTableGateway();
		RecordSet rs;
		try 
		{
			rs = productTableGateway.getGamesByID(productID1);
			Product product = null;

			
			if(rs.getRowCount() ==1)
			{
				int productID = (Integer) rs.getValueAt(0, 0);
				String title =(String) rs.getValueAt(0, 1);
				String console = (String) rs.getValueAt(0, 2);
				String category = (String) rs.getValueAt(0, 3);
				String detail =(String)rs.getValueAt(0, 4);
				int price = (Integer)rs.getValueAt(0, 5);
				
				product = new Product(productID, title, console, category, detail, price);
				
			}
			
			CurrentUserSession userss= (CurrentUserSession)request.getAttribute("userID");
			//System.out.println("TEST TEST TEST users NAME: "+ userss.toString());
			Cart cart  = new Cart(sessionID , userID, product);
			//HttpSession sessionTemp;// = response.getSession().getAttribute("userID")
			
			SessionHandler sessionHandler = new SessionHandler();
			
			//request.getSession().setAttribute("cart", cart);
			thisContext.setAttribute("cart", cart);
			thisContext.setAttribute("session2", sessionHandler);
			//request.getSession().setAttribute("session2", sessionHandler);
			response.sendRedirect("CartJSP.jsp");
		} 
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
	
	}

}
